import { createRouter, createWebHashHistory, NavigationGuardNext, RouteLocationNormalized } from 'vue-router'
import { routes } from './module/base-routes'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useUserStore } from "../store/user";
import {  GetParamUrl } from '@/api/publicTool';
import { getMenuButtonList } from '@/api/overallAuthApi';
import { ButtonRoleTypeEnum } from '@/enum/public';

NProgress.configure({ showSpinner: false })

const router = createRouter({
  history: createWebHashHistory(), //开发环境
  routes
})

/**
路由守卫，访问路由菜单前拦截
 * @param to 目标
 * @param from 来至 
 */
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
  NProgress.start();
  const userStore = useUserStore();
  if (userStore.initialized) {
    userStore.loadMenus();
    userStore.initialized = false;
  }
  const endTime = new Date(userStore.expiresDate);
  const currentTime = new Date();
  to.fullPath = to.path + "?MenuId=" + to.meta.Id;
  var time = isNaN(endTime.getTime()) ? null : endTime;
  if ((to.meta.RequireAuth && time == null) || (to.meta.RequireAuth && endTime < currentTime)) {
    router.push('/login')
  }
  else if (to.meta.RequireAuth) {
    next();
  } else if (to.matched.length == 0) {
    next({ path: '/panel' })
  } else {
    next();
  }
})

router.afterEach(() => {
  var menuId = GetParamUrl("MenuId");
  const userStore = useUserStore();
  const endTime = new Date(userStore.expiresDate);
  const currentTime = new Date();
  if (userStore.token !== '' && endTime > currentTime) {
    userStore.buttonAuth = [];
    getMenuButtonList({
      menuId: menuId,
      buttonRoleType: ButtonRoleTypeEnum.RowButton,
    }).then(({ data, code }) => {
      if (code == 200) {
        userStore.buttonAuth = data;
      }
    });
  }
  NProgress.done();
})

export default router